package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.ExchangeGift;
import cn.wolfcode.crm.domain.Gift;
import cn.wolfcode.crm.domain.Member;
import cn.wolfcode.crm.mapper.ExchangeGiftMapper;
import cn.wolfcode.crm.mapper.GiftMapper;
import cn.wolfcode.crm.mapper.MemberMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IExchangeGiftService;
import cn.wolfcode.crm.util.LogicException;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PageUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ExchangeGiftServiceImpl implements IExchangeGiftService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private GiftMapper giftMapper;
    @Autowired
    private ExchangeGiftMapper mapper;

    //兑换积分
    public void change(Long cardno, Long totalCount, Long giftId) {

        //totalCount:兑换消费总积分
        Member info = memberMapper.queryByCardno(cardno);
        Gift gift = giftMapper.selectByPrimaryKey(giftId);
        if (totalCount / gift.getIntegral() > gift.getNumber()) {
            throw new LogicException("该礼品库存不足");
        }
        if (totalCount==0) {
            throw new LogicException("你,是不是忘记了什么");
        }
        if (totalCount > info.getAvailablepoint()) {
            throw new LogicException("哎呀,积分不足");
        }
        Long points = info.getAvailablepoint();
        //剩余积分
        points = Long.valueOf(points.longValue() - totalCount.longValue());
        memberMapper.updatePointsChange(cardno, points);

        //兑换完后减少库存
        gift.setNumber(gift.getNumber() - totalCount / gift.getIntegral());
        giftMapper.updateByPrimaryKey(gift);

        //添加兑换明细
        ExchangeGift exchangeItem = new ExchangeGift();
        exchangeItem.setMemberinfoCardno(info.getCardno());
        exchangeItem.setMemberinfoName(info.getName());
        exchangeItem.setGiftName(gift.getName());
        exchangeItem.setNumber(totalCount / gift.getIntegral());
        exchangeItem.setMemberinfoAvailablepoint(points);
        exchangeItem.setGiftIntegral(totalCount);
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        exchangeItem.setInputuserUsername(employee.getUsername());
        exchangeItem.setExchangedate(new Date());
        mapper.insert(exchangeItem);
    }


    public PageResult query(QueryObject qo) {
        return PageUtils.query(qo, mapper);
    }

    public List<ExchangeGift> list() {
        return mapper.selectAll();
    }
}
